package com.ywk.base.dataStructure.hashtab;
//哈希表
public class HashTabDemo {

	public static void main(String[] args) {
		HashTab hashTab=new HashTab(7);
		Emp emp1=new Emp(01, "agb");
		hashTab.hashAdd(emp1);
		hashTab.showHashTab();
	}

}

class HashTab{
	private EmpLinkedList[] empLinkedLists;
	private int size;

	public HashTab(int size) {
		super();
		this.size = size;
		empLinkedLists=new EmpLinkedList[size];
		for (int i = 0; i < size; i++) {
			empLinkedLists[i]=new EmpLinkedList();
		}
	}
	
	public void hashAdd(Emp emp) {
		int no=hashFun(emp.getId());
		empLinkedLists[no].add(emp);
	}
	
	//编写散列函数
	public int hashFun(int no) {
		return no % size;
	}
	
	public void showHashTab() {
		for (int i = 0; i < size; i++) {
			empLinkedLists[i].showLinkedList(i);
		}
	}
}

class EmpLinkedList{
	private Emp head;
	
	public void add(Emp emp) {
		if(head==null) {
			head=emp;
		}
		Emp curEmp=head;
		while(true) {
			if(curEmp.next==null) {
				break;
			}
			curEmp=curEmp.next;
		}
		curEmp=emp.next;
	}
	
	public void showLinkedList(int no) {
		if(head==null) {
			System.out.println("Hash表第"+(no+1)+"条链表为空");
		}else {
			System.out.print("Hash表第"+(no+1)+"条链表中的元素有：");
			Emp curEmp=head;
			while(true) {
				System.out.print(curEmp+" ");
				if(curEmp.next==null) {
					break;
				}
				curEmp=curEmp.next;
			}
			System.out.println();
		}
	}
}

class Emp{
	private int id;
	private String name;
	public Emp next;
	
	public Emp(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "[id=" + id + ",name=" + name + "]";
	}
	
	
}